﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Portal.Nhibernate.Repository;
namespace Portal.Web.Areas.Admin.Controllers
{
    public class ArticleController : BaseAdminController
    {
        private readonly IArticleRepository<IArticle> _articleRepository;
        public ArticleController(IArticleRepository<IArticle> articleRepository)
        {
            _articleRepository = articleRepository;
        }
        public ArticleController()
        {
            _articleRepository = new ArticleRepository();
        }

        #region 文章管理页面及获取JSON数据
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获取文章列表
        /// </summary>
        /// <param name="queryModel">查询模型</param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        public ActionResult GetListJson(QueryModel queryModel, string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            return Json(_articleRepository.Get().Sorting(sort, order).SearchWhere(queryModel).Select(o => new Article { Id = o.Id, CreateTime = o.CreateTime, MainTitle = o.MainTitle, NormalImage = o.NormalImage, SmallImage = o.SmallImage, Culture = o.Culture }).JqEasyuiDataGrid(page, rows));
        }
        /// <summary>
        /// 新闻信息
        /// </summary>
        /// <returns></returns>
        public ActionResult News()
        {
            return View();
        }
        public ActionResult GetNewsJson(string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            return Json(_articleRepository.Get(o => o.CategoryId == ((int)CategoryArticleEnum.News).ToString(CultureInfo.InvariantCulture)).Sorting(sort, order).Select(o => new Article { Id = o.Id, CreateTime = o.CreateTime, MainTitle = o.MainTitle, NormalImage = o.NormalImage, SmallImage = o.SmallImage, Culture = o.Culture }).JqEasyuiDataGrid(page, rows));
        }
        public ActionResult TechnologyConsulting()
        {
            return View();
        }
        public ActionResult GetTechnologyConsultingJson(Portal.QueryModel queryModel, string sort = "Sort", string order = "DESC", int page = 1, int rows = 10)
        {
            return Json(_articleRepository.Get(o => o.CategoryId == ((int)CategoryArticleEnum.TechnologyConsulting).ToString(CultureInfo.InvariantCulture)).SearchWhere(queryModel).Sorting(sort, order).Select(o => new Article { Id = o.Id, CreateTime = o.CreateTime, MainTitle = o.MainTitle, NormalImage = o.NormalImage, SmallImage = o.SmallImage, Culture = o.Culture }).JqEasyuiDataGrid(page, rows));
        }
        #endregion

        #region 文章查询页面
        public ActionResult SearchControl()
        {
            return View();
        }
        public ActionResult SearchNewsControl()
        {
            return View();
        }
        public ActionResult SearchTechnologyConsultingControl()
        {
            return View();
        }
        #endregion



        /// <summary>
        /// Kndeditor文件上传
        /// </summary>
        /// <returns></returns>
        public void UploadFileArticleJson()
        {
            var kndeditor = new KndeditorHelper(System.Web.HttpContext.Current, "Article", CurrentUserName);
            kndeditor.UploadJson();
        }
        /// <summary>
        /// Kndeditor文件管理
        /// </summary>
        public void FileManagerArticleJson()
        {
            var kndeditor = new KndeditorHelper(System.Web.HttpContext.Current, "Article", CurrentUserName);
            kndeditor.FileManagerJson();
        }
        
        public ActionResult Create(string categoryId)
        {
            var model = _articleRepository.CreateEntity();
            model.CategoryId = categoryId;
            if (Request.IsAjaxRequest())
                return View("CreateControl", model);
            return View(model);
        }
        public ActionResult CreateNewsControl()
        {
            var model = _articleRepository.CreateEntity();
            model.CategoryId = ((int)CategoryArticleEnum.News).ToString(CultureInfo.InvariantCulture);
            return View(model);
        }
        public ActionResult CreateTechnologyConsultingControl()
        {
            var model = _articleRepository.CreateEntity();
            model.CategoryId = ((int)CategoryArticleEnum.TechnologyConsulting).ToString(CultureInfo.InvariantCulture);
            return View(model);
        }
    
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection, Article entity, HttpPostedFileBase articleImage, HttpPostedFileBase articleSmallImage)
        {
            var model = _articleRepository.CreateEntity();
            model.Author = entity.Author;
            model.SubTitle = entity.SubTitle;
            model.MainTitle = entity.MainTitle;
            model.Founder = CurrentUserName;
            model.Culture = entity.Culture ?? Culture;
            model.Content = entity.Content;
            model.IsRecommend = entity.IsRecommend;
            model.CategoryId = entity.CategoryId;
            if (Request.IsAjaxRequest())
            {
                _articleRepository.Add(model);
                _articleRepository.Save();
                return Json(new AjaxResult { state = true, message = "添加成功" });
            }
            if (articleImage != null)
            {
                var upload = new UploadHelper(articleImage, "/Upload/Article/") { IsImage = true, PicMaxLength = 1024 * 1000 };
                if (!upload.Save())
                {
                    TempData["Result"] = upload.ErrorMessage;
                    return View(model);
                }
                model.NormalImage = upload.FileRelativePath;
            }
            if (articleSmallImage != null)
            {
                var upload = new UploadHelper(articleSmallImage, "/Upload/Article/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                if (!upload.Save())
                {
                    TempData["Result"] = upload.ErrorMessage;
                    return View(model);
                }
                model.SmallImage = upload.FileRelativePath;
            }
            else
            {
                if (!string.IsNullOrEmpty(model.NormalImage.NullSafe()))
                {
                    model.SmallImage = model.NormalImage.Insert(
                        model.NormalImage.LastIndexOf("/", StringComparison.Ordinal) + 1, "jpeg-");
                    var xImage = new XImage();
                    xImage.ToThumbnail(model.NormalImage,
                                       model.NormalImage.Insert(
                                           model.NormalImage.LastIndexOf("/", System.StringComparison.Ordinal) + 1,
                                           "jpeg-"), 150, 150);
                }
            }
            _articleRepository.Add(model);
            _articleRepository.Save();
            ViewData["Result"] = new AjaxResult { state = true, message = "添加成功" };
            return Create(model.CategoryId);


        }
       
        public ActionResult Edit(string id)
        {
            var model = _articleRepository.Get().SingleOrDefault(o => o.Id == id);
            if (Request.IsAjaxRequest())
                return View("EditControl", model);
            return View(model);
        }
        public ActionResult EditNewsControl(string id)
        {
            var model = _articleRepository.Get().SingleOrDefault(o => o.Id == id);
            return View(model);
        }
        public ActionResult EditTechnologyConsultingControl(string id)
        {
            var model = _articleRepository.Get().SingleOrDefault(o => o.Id == id);
            return View(model);
        }
        /// <summary>
        /// 保存产品信息
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="entity"></param>
        /// <param name="articleImage"></param>
        /// <param name="articleSmallImage"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(FormCollection collection, Article entity, HttpPostedFileBase articleImage, HttpPostedFileBase articleSmallImage)
        {

            var model = _articleRepository.Get().SingleOrDefault(o => o.Id == entity.Id);
            if (model != null)
            {
                model.Author = entity.Author;
                model.SubTitle = entity.SubTitle;
                model.MainTitle = entity.MainTitle;
                model.Founder = CurrentUserName;
                model.Culture = entity.Culture ?? Culture;
                model.Content = entity.Content;
                model.IsRecommend = entity.IsRecommend;
                if (!Request.IsAjaxRequest())
                {


                    if (articleImage != null)
                    {
                        var upload = new UploadHelper(articleImage, "/Upload/Article/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                        if (!upload.Save())
                        {
                            TempData["Result"] = upload.ErrorMessage;
                            return View(model);
                        }
                        model.NormalImage = upload.FileRelativePath;
                    }
                    if (articleSmallImage != null)
                    {
                        var upload = new UploadHelper(articleSmallImage, "/Upload/Article/") { IsImage = true, PicMaxLength = 1000 * 1024 };
                        if (!upload.Save())
                        {
                            TempData["Result"] = upload.ErrorMessage;
                            return View(model);
                        }
                        model.SmallImage = upload.FileRelativePath;
                    }
                    else
                    {
                        if (articleImage != null && !string.IsNullOrEmpty(model.NormalImage.NullSafe()))
                        {
                            model.SmallImage = model.NormalImage.Insert(
                                  model.NormalImage.LastIndexOf("/", StringComparison.Ordinal) + 1, "jpeg-");
                            var xImage = new XImage();
                            xImage.ToThumbnail(model.NormalImage, model.NormalImage.Insert(model.NormalImage.LastIndexOf("/", System.StringComparison.Ordinal) + 1, "jpeg-"), 150, 150);
                        }
                    }
                }
                _articleRepository.Update(model);
                _articleRepository.Save();
                if (!Request.IsAjaxRequest())
                {
                    ViewData["Result"] = new AjaxResult { message = "修改成功" };
                    return View(model);
                }
                return Json(new AjaxResult { message = "修改成功", state = true });
            }
            if (!Request.IsAjaxRequest())
                return NotFount(new AjaxResult { message = "记录不存在" });
            return Json(new AjaxResult { message = "记录不存在", state = false });
        }
        [HttpPost]
        public ActionResult Delete(List<string> id, FormCollection collection)
        {
            var list = _articleRepository.Get().Where(o => id.Contains(o.Id));
            list.ForEach(o => _articleRepository.Delete(o));
            _articleRepository.Save();
            return Json(new AjaxResult { state = true, message = "删除成功" });
        }

    }
}
